package com.cubeofnine.sugar;

import com.cubeofnine.sugar.service.element.DatabaseElement;
import com.cubeofnine.sugar.service.element.ErrorValue;
import com.cubeofnine.sugar.service.element.LoginResult;
import com.cubeofnine.sugar.business.LoginBusiness;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends ActivityImpt {
	private static LoginBusiness loginBusiness = null;

	private static EditText username = null;
	private static EditText password = null;
	private static EditText sugarcrmUrl = null;
	private static CheckBox rememberPassword = null;
	private static CheckBox automaticLogin = null;

	private static Button loginBtn = null;
	private static Button forgotPasswordBtn = null;

	// Thread and Handler Variables
	private static Handler handler;
	private Thread thread;

	private static Context context = null;

	public static String getClassName() {
		return LoginActivity.class.getName();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(getClassName(), "onCreate() : Start");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		context = this;

		boolean skipLogin = false;
		try {
			skipLogin = getIntentParams().getBoolean(SKIP_LOGIN);
		} catch (Exception e) {
			skipLogin = false;
		}

		Log.d(getClassName(), "skipLogin = " + skipLogin);

		try {
			loginBusiness = new LoginBusiness(this);

			username = (EditText) findViewById(R.id.text_username);
			password = (EditText) findViewById(R.id.text_password);
			sugarcrmUrl = (EditText) findViewById(R.id.text_sugarcrm_url);
			rememberPassword = (CheckBox) findViewById(R.id.check_remember_password);
			automaticLogin = (CheckBox) findViewById(R.id.check_automatic_login);
			loginBtn = (Button) findViewById(R.id.button_login);
			forgotPasswordBtn = (Button) findViewById(R.id.button_forgot_password);

			boolean isOnline = isOnline();

			Log.d(getClassName(), "isOnline = " + isOnline);
			if (isOnline) {
				// Create a handler to update the UI
				handler = new Handler();

				// Check if the thread is already running
				thread = (Thread) getLastNonConfigurationInstance();
				if (thread != null && thread.isAlive()) {
					initProgressDialog("Logging in...");
				} else {
					try {
						DatabaseElement element = loginBusiness
								.getDefaultValue();

						if (element != null) {
							username.setText(element.getUsername());
							sugarcrmUrl.setText(element.getSugarUrl());
							rememberPassword.setChecked(element
									.isRememberPassword());

							if (rememberPassword.isChecked()) {
								password.setText(element.getPassword());
								automaticLogin.setChecked(element
										.isAutomaticLogin());
							}
						}

						Log.d(getClassName(), "rememberPassword = "
								+ rememberPassword.isChecked());
						Log.d(getClassName(), "automaticLogin = "
								+ automaticLogin.isChecked());

						if (!skipLogin && automaticLogin.isChecked()) {
							onClickLoginButton(null);
						}
					} catch (Exception e) {
						Log.e(getClassName(), "onCreate()", e);
						alertDialog(R.string.msg_application_error);
					}
				}
			} else {
				changeItemEnabled(false);
				alertDialog(R.string.msg_no_connection);
			}
		} catch (Exception e) {
			Log.e(getClassName(), "onCreate()", e);
			alertDialog(R.string.msg_application_error);
		}

		Log.i(getClassName(), "onCreate() : End");
	}

	public void onDestroy() {
		Log.i(getClassName(), "onDestroy() : Start");

		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}

		Log.i(getClassName(), "onDestroy() : End");
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		moveTaskToBack(true);
		closeApplication();
	}

	// Save the thread
	@Override
	public Object onRetainNonConfigurationInstance() {
		Log.d(getClassName(), "onRetainNonConfigurationInstance()");
		return thread;
	}

	public static void changeItemEnabled(boolean enabled) {
		Log.i(getClassName(), "changeItemEnabled() : Start");

		username.setEnabled(enabled);
		password.setEnabled(enabled);
		sugarcrmUrl.setEnabled(enabled);
		rememberPassword.setEnabled(enabled);
		automaticLogin.setEnabled(enabled);
		loginBtn.setEnabled(enabled);
		forgotPasswordBtn.setEnabled(enabled);

		Log.i(getClassName(), "changeItemEnabled() : End");
	}

	public void onClickRememberPassword(View view) {
		Log.i(getClassName(), "onClickRememberPassword() : Start");

		if (rememberPassword.isChecked()) {
			automaticLogin.setEnabled(true);
		} else {
			automaticLogin.setChecked(false);
			automaticLogin.setEnabled(false);
		}

		Log.i(getClassName(), "onClickRememberPassword() : End");
	}

	public void onClickLoginButton(View view) {
		Log.i(getClassName(), "onClickLoginButton() : Start");
		boolean isOnline = isOnline();

		Log.d(getClassName(), "isOnline = " + isOnline);

		if (isOnline) {
			String usernameValue = username.getText().toString();
			String passwordValue = password.getText().toString();
			String sugarcrmUrlValue = sugarcrmUrl.getText().toString();

			Log.d(getClassName(), "usernameValue = " + usernameValue);
			Log.d(getClassName(), "passwordValue = " + passwordValue);
			Log.d(getClassName(), "sugarcrmUrlValue = " + sugarcrmUrlValue);

			if (usernameValue.length() == 0) {
				alertDialog(R.string.msg_username_not_empty);
			} else if (passwordValue.length() == 0) {
				alertDialog(R.string.msg_password_not_empty);
			} else if (sugarcrmUrlValue.length() == 0) {
				alertDialog(R.string.msg_sugar_url_not_empty);
			} else {
				try {
					boolean isValid = loginBusiness
							.checkUsernamePasswordFormat(usernameValue,
									passwordValue);

					Log.d(getClassName(), "isValid = " + isValid);

					if (isValid) {
						initProgressDialog("Logging in...");

						thread = new LoginThread();
						thread.start();
					} else {
						alertDialog(R.string.msg_username_or_password_invalid);
					}
				} catch (Exception e) {
					Log.e(getClassName(), "onClickLoginButton()", e);
					alertDialog(R.string.msg_application_error);
				}
			}
		} else {
			changeItemEnabled(false);
			alertDialog(R.string.msg_no_connection);
		}

		Log.i(getClassName(), "onClickLoginButton() : End");
	}

	public void onClickForgotPasswordButton(View view) {
		Log.i(getClassName(), "onClickForgotPasswordButton() : Start");
		boolean isOnline = isOnline();

		Log.d(getClassName(), "isOnline = " + isOnline);

		if (isOnline) {
			gotoActivity(ForgotPasswordActivity.class);
		} else {
			changeItemEnabled(false);
			alertDialog(R.string.msg_no_connection);
		}

		Log.i(getClassName(), "onClickForgotPasswordButton() : End");
	}

	static public class LoginThread extends Thread {
		String usernameValue = username.getText().toString();
		String passwordValue = password.getText().toString();
		String sugarcrmUrlValue = sugarcrmUrl.getText().toString();
		boolean isRememberPassword = rememberPassword.isChecked();
		boolean isAutomaticLogin = automaticLogin.isChecked();

		public static String getClassName() {
			return LoginThread.class.getName();
		}

		@Override
		public void run() {
			Log.i(getClassName(), "run() : Start");

			try {
				errorMessage = null;
				loginBusiness.saveValue(usernameValue, passwordValue,
						sugarcrmUrlValue, isRememberPassword, isAutomaticLogin,
						"", false);

				loginBusiness.connectSugarCrmWebService(sugarcrmUrlValue);

				LoginResult result = loginBusiness.login(usernameValue,
						passwordValue);

				if (result == null) {
					errorMessage = context
							.getString(R.string.msg_connection_error);
				} else {
					String sessionId = result.getId();
					int errorNumber = 0;

					ErrorValue error = result.getErrorValue();
					if (error != null) {
						errorNumber = error.getNumber();
						errorMessage = error.getDescription();
					}

					Log.d(getClassName(), "sessionId = " + sessionId);
					Log.d(getClassName(), "errorNumber = " + errorNumber);
					Log.d(getClassName(), "errorMessage = " + errorMessage);

					if (errorNumber == 0) {
						boolean isUserAdmin = loginBusiness
								.isUserAdmin(sessionId);
						Log.d(getClassName(), "isUserAdmin = " + isUserAdmin);

						errorMessage = null;
						loginBusiness.saveValue(usernameValue, passwordValue,
								sugarcrmUrlValue, isRememberPassword,
								isAutomaticLogin, sessionId, isUserAdmin);
						changeItemEnabled(true);

						if (isUserAdmin) {
							gotoActivity(ModuleActivity.class);
						} else {
							gotoActivity(SalesActivity.class);
						}
					}
				}
			} catch (Exception e) {
				Log.e(getClassName(), "Connection Error", e);
				errorMessage = context.getString(R.string.msg_connection_error);
			} finally {
				Log.d(getClassName(), "Finally");
				handler.post(new LoginRunnable());
			}

			Log.i(getClassName(), "run() : End");
		}
	}

	static public class LoginRunnable implements Runnable {
		public static String getClassName() {
			return LoginRunnable.class.getName();
		}

		public void run() {
			Log.i(getClassName(), "run() : Start");
			Log.d(getClassName(), "errorMessage = " + errorMessage);

			if (errorMessage != null && !"".equals(errorMessage.trim())) {
				((ActivityImpt) context).alertDialog(errorMessage);
			}

			dialog.dismiss();

			Log.i(getClassName(), "run() : End");
		}
	}
}